//
//  NetworkTools.swift
//  SinaWeibo
//
//  Created by liyue on 15/11/21.
//  Copyright © 2015年 李越. All rights reserved.
//

import UIKit
import AFNetworking

private let weiboDomain = "com.baidu.data.error"

enum HTTPMethod: String {
    
    case POST = "POST"
    case GET = "GET"
}

class NetworkTools: AFHTTPSessionManager {

    //定义单例对象
    static let sharedTools: NetworkTools = {
        
        let urlString = "https://api.weibo.com/"
        let url = NSURL(string: urlString)
        let tools = NetworkTools(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    func requestJsonDict(method: HTTPMethod, urlString: String, parmaters: [String : AnyObject]?, finished: (result: [String : AnyObject]?, error: NSError?) -> ()) {
        
        if method == HTTPMethod.GET {
            GET(urlString, parameters: parmaters, success: { (_, result) -> Void in
                
                if let dict = result as? [String : AnyObject] {
                    finished(result: dict, error: nil)
                    return
                }
                let dataError = NSError(domain: weiboDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey : "数据错误"])
                finished(result: nil, error: dataError)
                }) { (_, error) -> Void in
                    finished(result: nil, error: error)
            }
        } else {
        
        POST(urlString, parameters: parmaters, success: { (_, result) -> Void in
            
            if let dict = result as? [String : AnyObject] {
                finished(result: dict, error: nil)
                return
            }
            let dataError = NSError(domain: weiboDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey : "数据错误"])
            finished(result: nil, error: dataError)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
            }
        }
    }
}
